package com.whjk.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.whjk.core.common.api.Result;
import com.whjk.system.biz.service.*;
import com.whjk.system.data.dto.WhjkPersonResultDto;
import com.whjk.system.data.entity.*;
import com.whjk.system.biz.mapper.WhjkTemplateMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whjk.system.data.uitls.DocTestUtil;
import com.whjk.system.data.vo.InspectVo;
import com.whjk.system.data.vo.SVo;
import com.whjk.system.data.vo.TemplateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 模板 服务实现类
 * </p>
 *
 * @author hl
 * @since 2023-06-28
 */
@Slf4j
@Service
public class WhjkTemplateServiceImpl extends ServiceImpl<WhjkTemplateMapper, WhjkTemplate> implements WhjkTemplateService {
    @Autowired
    private WhjkPackageRelService whjkPackageRelService;
    @Autowired
    private WhjkPackageRelInfoService whjkPackageRelInfoService;
    @Autowired
    private WhjkZhxmService whjkZhxmService;
    @Autowired
    private WhjkXmService whjkXmService;
    @Autowired
    private WhjkPersonService whjkPersonService;
    @Autowired
    private WhjkTjbgzswhService whjkTjbgzswhService;
    @Autowired
    private WhjkBblxService whjkBblxService;
    @Autowired
    private WhjkTeamCheckInfoService whjkTeamCheckInfoService;

    @Override
    public Page<TemplateVo> pageList(TemplateVo templateVo) {
        return this.baseMapper.templatePageList(new Page<>(templateVo.getCurrent(), templateVo.getSize()),templateVo);
    }

    @Override
    public String getTemplateText(String relId)throws Exception{
        WhjkPackageRel rel = whjkPackageRelService.getById(relId);
        Assert.isTrue(rel != null, "查询模板信息失败: 未查到数据！");

        SVo template = getSvo(rel);
        log.info("SVo template:"+new Gson().toJson(template));
        //Assert.isTrue(true, "查询模板信息失败: 未查到数据！");
        // 一个模板查询方法
        List<WhjkTemplate> list = this.list(new LambdaQueryWrapper<WhjkTemplate>()
                .eq(WhjkTemplate::getStatus, 1)
                .eq(WhjkTemplate::getDelFlag, 0)
                .eq(StringUtils.isNotBlank(rel.getXmId()), WhjkTemplate::getZhxmId, rel.getXmId()));
        Assert.isTrue(!list.isEmpty(), "查询模板信息失败: 当前项目没有模板");
        WhjkTemplate res = list.get(0);
        Assert.isTrue(res != null && StringUtils.isNotBlank(res.getContent()), "查询模板信息失败: 当前项目没有模板文件，请上传");
        log.info("WhjkTemplate:"+new Gson().toJson(res));
        String templateDocx = res.getContent();
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        template.setDate(df.format(new Date()));
        String html = "";
        if (templateDocx.contains(".docx")) {
            html = DocTestUtil.readWord(templateDocx, template);
        }
        Assert.isTrue(StringUtils.isNotBlank(html), "预览模板信息异常: 转换文件失败");
        return html.trim();
    }

    private SVo getSvo(WhjkPackageRel rel) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        SVo v = new SVo();
        WhjkPerson pe = whjkPersonService.getById(rel.getPeId());

        WhjkTeamCheckInfo comp = whjkTeamCheckInfoService.getById(pe.getTeamId());
        v.setUnitName(comp == null ? "" : comp.getTeamName());

        WhjkTjbgzswh bgzswh = whjkTjbgzswhService.getOne(new LambdaQueryWrapper<WhjkTjbgzswh>()
                .eq(WhjkTjbgzswh::getLx, 3)
                .eq(WhjkTjbgzswh::getDelFlag, 0)
        );
        v.setHospitalName(bgzswh == null ? "" : bgzswh.getName());

        BeanUtils.copyProperties(pe, v);
        v.setCreateTime(pe.getCreateTime().toLocalDate() + " " + pe.getCreateTime().toLocalTime());
        v.setDoctor(pe.getAuditDoctor());
        v.setMobile(pe.getPhone());

        v.setHeadImg(pe.getUserImage());
        v.setSex(pe.getGender().equals("1") ? "男" : "女");
        v.setSectionOffice("体检科");
        v.setTestNum(pe.getRegSerialNo());
        String isMarry = "";
        switch (StringUtils.isBlank(pe.getMarriage()) ? 10 : Integer.parseInt(pe.getMarriage())) {
            case 0:
                isMarry = "未婚";
                break;
            case 1:
                isMarry = "已婚";
                break;
            case 2:
                isMarry = "离婚";
                break;
            case 3:
                isMarry = "丧偶";
                break;
            default:
                isMarry = "其他";
                break;
        }
        v.setIsMarry(isMarry);

        v.setReportDoctor(rel.getCheckDoctor());
        v.setReviewDoctor(rel.getReviewDoctor());

        WhjkPersonResultDto r = whjkPackageRelInfoService.getPersonResult(rel.getId());

        if ("1".equals(r.getWhjkPackageRel().getJclx())) {
            //常规检查，
            prepareNormalCheck(rel, v, r);
            v.setPrintDate(pe.getPrintTime() == null ? LocalDateTime.now().format(formatter) : pe.getPrintTime().format(formatter));

        } else if ("3".equals(r.getWhjkPackageRel().getJclx())) {
            //功能检查 CT DR 彩超
            v.setInspectResult(r.getWhjkPackageRel().getAuxiliaraResult());
            v.setCheckMethod("CT DR 彩超");
            v.setProjectNameTemplate(r.getWhjkPackageRel().getCheckPart());
            v.setInspectDate(r.getWhjkPackageRel().getCheckTime().toLocalDate());
            v.setOpinion(r.getWhjkPackageRel().getSummarize());
        } else {
            //常规检查，检验检测，
            v.setInspectTime(r.getWhjkPackageRel().getCheckTime().toLocalDate() + " " + r.getWhjkPackageRel().getCheckTime().toLocalTime());
            v.setSpecimen(r.getWhjkPackageRel().getBbmc());
            v.setTableMonitoring(r.getItemList().stream().map(i -> {
                InspectVo sv = new InspectVo();
                sv.setNum("" + i.getXssx());
                sv.setMonitorName(i.getJcxmName());
                sv.setUnit(i.getDw());
                sv.setValue(i.getCheckResult());
                Integer key = i.getCheckResult() == null ? 0 : Integer.parseInt(i.getCheckResult());
                switch (key) {
                    case 0:
                        sv.setArrow("");
                        break;
                    case 1:
                        sv.setArrow("");
                        break;
                    case 2:
                        sv.setArrow("↑");
                        break;
                    case 3:
                        sv.setArrow("↓");
                        break;
                    case 4:
                        sv.setArrow("↑");
                        break;
                    case 5:
                        sv.setArrow("↓");
                        break;
                    case 6:
                        sv.setArrow("↑");
                        break;
                    case 7:
                        sv.setArrow("↓");
                        break;
                    default:
                        sv.setArrow("");
                        break;
                }
                sv.setResultTips("" + i.getIsAbnormal());
                String min = i.getSzxx() == null ? "" : i.getSzxx();
                String max = i.getSzsx() == null ? "" : i.getSzsx();
                sv.setReferenceRange(min + "--" + max);
                return sv;
            }).sorted(Comparator.comparing(n -> Integer.parseInt(n.getNum()))).collect(Collectors.toList()));
        }

        return v;
    }

    /**
     * 常规体检表
     *
     * @param rel
     * @param v
     * @param r
     */
    private void prepareNormalCheck(WhjkPackageRel rel, SVo v, WhjkPersonResultDto r) {
        r.getItemList().stream().forEach(i -> {
            System.out.println(new Gson().toJson(i));
            if (i.getJcxmName().contains("心率") || i.getJcxmName().contains("心跳")
                    || i.getJcxmName().contains("脉率") || i.getJcxmName().contains("脉搏")) {
                v.setHeartRate(i.getCheckResult() + i.getDw());
            }
            if (i.getJcxmName().equals("心肺")) {
                v.setXinFei(i.getCheckResult());
            }
            if (i.getJcxmName().equals("心")) {
                v.setXin(i.getCheckResult());
            }
            if (i.getJcxmName().equals("肺")) {
                v.setFei(i.getCheckResult());
            }
            if (i.getJcxmName().contains("脾")) {
                v.setPi(i.getCheckResult());
            }
            if (i.getJcxmName().contains("肝")) {
                v.setGan(i.getCheckResult());
            }
            if (i.getJcxmName().contains("过敏史")) {
                v.setGuoMinShi(i.getCheckResult());
            }
            if (i.getJcxmName().contains("既往史")) {
                v.setJiWangShi(i.getCheckResult());
            }
            if (i.getJcxmName().contains("身高")) {
                v.setHeight(i.getCheckResult() + i.getDw());
            }
            if (i.getJcxmName().contains("体重")) {
                v.setWeight(i.getCheckResult() + i.getDw());
            }
            if (i.getJcxmName().contains("辨色力")) {
                v.setColorVision(i.getCheckResult());
            }
            if (i.getJcxmName().contains("裸眼视力(左)")) {
                v.setNakedVisionLeft(i.getCheckResult());
            }
            if (i.getJcxmName().contains("裸眼视力(右)")) {
                v.setNakedVisionRight(i.getCheckResult());
            }
            if (i.getJcxmName().contains("舒张压")) {
                v.setBloodLow(Integer.parseInt(i.getCheckResult()));
            }
            if (i.getJcxmName().contains("收缩压")) {
                v.setBloodHight(Integer.parseInt(i.getCheckResult()));
            }
            if (i.getJcxmName().contains("腹部")) {
                v.setFuBu(i.getCheckResult());
            }
            if (i.getJcxmName().contains("淋巴")) {
                v.setLinBa(i.getCheckResult());
            }
            if (i.getJcxmName().contains("脊柱四肢")) {
                v.setJiZhuSiZhi(i.getCheckResult());
            }
            if (i.getJcxmName().equals("四肢")) {
                v.setSiZhi(i.getCheckResult());
            }
            if (i.getJcxmName().contains("辅助检查")) {
                v.setFuZhuJianCha(i.getCheckResult());
            }
            if (i.getJcxmName().contains("外科其他")) {
                v.setWaiKeQiTa(i.getCheckResult());
            }
            if (i.getJcxmName().equals("其他")) {
                v.setOther(i.getCheckResult());
            }
            if (i.getJcxmName().contains("推荐单位")) {
                v.setTuiJianUnit(i.getCheckResult());
            }
            if (i.getJcxmName().contains("内科")) {
                v.setNeiKe(i.getCheckResult());
            }
            if (i.getJcxmName().contains("外科")) {
                v.setWaiKe(i.getCheckResult());
            }
            if (i.getJcxmName().contains("皮肤")) {
                v.setPiFu(i.getCheckResult());
            }
        });

        v.setBloodPressure(v.getBloodHight() + "mmHg/" + v.getBloodLow() + "mmHg");
        v.setCheckOpinion(r.getWhjkPackageRel().getSummarize());
    }

}
